/*************************************************************
 * Title: UserResource.java
 * Description: 
 * Author: Huang Shaobin
 * Email: shaobin.software@gmail.com
 * CreateTime: Feb 25, 2013 2:39:37 PM
 * Description:
 ************************************************************/
package snow.biz.system.web.rest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.restlet.data.Form;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import snow.biz.security.model.Privilege;
import snow.biz.security.model.Role;
import snow.biz.security.service.IPrivilegeService;
import snow.biz.security.service.IRoleService;
import snow.biz.system.model.User;
import snow.biz.system.service.IUserService;
import snow.core.enums.Status;
import snow.core.exceptions.BusinessException;
import snow.core.persistence.AndedConditions;
import snow.core.persistence.BinaryOperator;
import snow.core.persistence.Condition;
import snow.core.persistence.Conditions;
import snow.core.persistence.Order;
import snow.core.security.Operator;
import snow.core.security.annotations.Operation;
import snow.core.security.annotations.Resource;
import snow.core.web.rest.ResourceSupport;

/**
 * 用户相关的REST接口
 */
@Path("/system/users")
@Resource(uri = "/users")
public class UserResource extends ResourceSupport implements InitializingBean {

	private String defaultLoginPass = "123456";
	private Integer defaultRoleId; // 默认角色主键
	private IUserService userService;
	private IRoleService roleService;
	private IPrivilegeService privilegeService;

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "创建用户", type = Operator.CREATE)
	public Object addUser() throws BusinessException {
		final Form postForm = super.getPostAsForm();
		final User currentUser = userService.getCurrentUser();
		final String loginName = postForm.getFirstValue("loginName");
		final String loginPass = postForm.getFirstValue("loginPass");
		final Role role = roleService.searchRoleFrom(defaultRoleId);
		final Set<Role> roles = new HashSet<Role>(Arrays.asList(new Role[] { role }));
		User newUser = new User(currentUser, Status.SUCCESS, loginName, loginPass, roles);
		userService.createUserFrom(newUser); // 持久化到数据库
		return getSuccessResult();
	}

	public void afterPropertiesSet() throws Exception {
		Assert.notNull(defaultLoginPass, "The property [defaultLoginPass] must not be null!");
		Assert.notNull(defaultRoleId, "The property [defaultRoleId] must not be null!");
		Assert.notNull(userService, "The property [userService] must not be null!");
		Assert.notNull(roleService, "The property [roleService] must not be null!");
		Assert.notNull(privilegeService, "The property [privilegeService] must not be null!");
	}

	@DELETE
	@Path("/{id:\\d+}")
	@Resource(uri = "/{id:\\d+}")
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "删除用户", type = Operator.REMOVE)
	public Object delUser(@PathParam("id")
	Integer id) {
		return getSuccessResult();
	}

	public String getDefaultLoginPass() {
		return defaultLoginPass;
	}

	public Integer getDefaultRoleId() {
		return this.defaultRoleId;
	}

	public IPrivilegeService getPrivilegeService() {
		return this.privilegeService;
	}

	public IRoleService getRoleService() {
		return this.roleService;
	}

	public IUserService getUserService() {
		return userService;
	}

	@GET
	@Path("/privileges")
	@Resource(uri = "/privileges")
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "获取当前用户的权限信息", type = Operator.SEARCH, needCheck = false)
	public Object listPrivileges() throws BusinessException {
		final User currentUser = userService.getCurrentUser();
		final Set<Role> roleSet = currentUser.getRoles();
		final Set<Privilege> privileges = new HashSet<Privilege>();
		if (CollectionUtils.isNotEmpty(roleSet)) {
			for (final Role role : roleSet) {
				if (role != null) {
					privileges.addAll(role.getPrivileges());
				}
			}
		}
		final Conditions conditions = new AndedConditions();
		conditions.addCondition(new Condition("needCheck", BinaryOperator.EQ, Privilege.NOT_NEED_CHECK));
		conditions.addCondition(new Condition("status", BinaryOperator.EQ, Status.SUCCESS));
		privileges.addAll(privilegeService.searchPrivilegesFrom(conditions, null, -1, -1));
		return privileges;
	}

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "显示用户列表", type = Operator.SEARCH)
	public Object listUsers() throws BusinessException {
		final Form queryForm = super.getQueryAsForm();
		final Conditions conditions = new AndedConditions();
		final String loginName = queryForm.getFirstValue("loginName");
		if (StringUtils.isNotBlank(loginName)) {
			conditions.addCondition(new Condition("loginName", BinaryOperator.LIKE, '%' + StringUtils.trim(loginName) + '%'));
		}
		final String statusVal = queryForm.getFirstValue("status");
		if (!"all".equalsIgnoreCase(statusVal)) {
			if ("failure".equalsIgnoreCase(statusVal)) {
				conditions.addCondition(new Condition("status", BinaryOperator.EQ, Status.FAILURE));
			} else {
				conditions.addCondition(new Condition("status", BinaryOperator.EQ, Status.SUCCESS));
			}
		}
		final int start = NumberUtils.toInt(queryForm.getFirstValue("start"), -1);
		final int limit = NumberUtils.toInt(queryForm.getFirstValue("limit"), -1);
		final List<Order> orders = new ArrayList<Order>();
		orders.add(Order.desc("id"));
		return userService.searchUsersForPagingFrom(conditions, orders, start, limit);
	}

	@PUT
	@Path("/{id:\\d+}")
	@Resource(uri = "/{id:\\d+}")
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "修改用户信息", type = Operator.MODIFY)
	public Object modUser(@PathParam("id")
	Integer id) {
		return null;
	}

	public void setDefaultLoginPass(String defaultLoginPass) {
		this.defaultLoginPass = defaultLoginPass;
	}

	public void setDefaultRoleId(Integer defaultRoleId) {
		this.defaultRoleId = defaultRoleId;
	}

	public void setPrivilegeService(IPrivilegeService privilegeService) {
		this.privilegeService = privilegeService;
	}

	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@GET
	@Path("/{id:\\d+}")
	@Resource(uri = "/{id:\\d+}")
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "显示用户信息", type = Operator.SEARCH, needCheck = false)
	public Object showUser(@PathParam("id")
	Integer id) {
		return null;
	}
}
